<?php

namespace app\components;

use yii\base\InvalidConfigException;
use yii\web\UrlManager;

class BaseUrlManager extends UrlManager {

    public $subDomain;

    /**
     * @throws InvalidConfigException
     */
    public function init() {
        $hostInfo = $this->getHostInfo();

        preg_match('~^(http://|https://)(\w+)\.([a-zA-z0-9_-]+)\.(\w+)?(\.(\w+))?$~iu', $hostInfo, $match);
        $this->subDomain = isset($match[2]) ? $match[2] : '';
        if(!empty($this->subDomain)){
            $this->subDomain = str_replace(['www', '1'], '', $this->subDomain);
        }
        return parent::init();
    }

    public function parseRequest($request) {
        $result = parent::parseRequest($request);
        if (!empty($this->subDomain) && strpos($result[0], $this->subDomain) === FALSE) {
            $result[0] = $this->subDomain . '/' . $result[0];
        }
        return $result;
    }

    public function createUrl($params) {
        if (!empty($this->subDomain) && strpos($params[0], $this->subDomain) !== FALSE) {
            $params[0] = str_replace($this->subDomain, '', $params[0]);
        }
        return parent::createUrl($params);
    }
}